'use strict';
// 引入 vk-unicloud
const vkCloud = require('vk-unicloud');
// 通过 vkCloud.createInstance 创建 vk 实例
const vk = vkCloud.createInstance({
	baseDir: __dirname,
	requireFn: require
});

var vkmail;
try {
	vkmail = require('vk-mail');
} catch (err) {
	console.error("请先添加公共模块：vk-mail");
}

exports.main = async (event, context) => {
	let res = { code: 0, msg: "" };
	
	let { config = {}, uniID } = vk.getUnicloud();
	


	let emailConfig = config.vk.service.email;

	let serviceType = "163";
	let {
		email,
		type
	} = event;
	
	if (!email) return { code:-1, msg:"email不能为空" };
	if (!type) return { code:-1, msg:"type不能为空" };

	let code = vk.pubfn.random(6);
	let subject = `验证码 ${code}`;
	let text = `验证码 ${code}，打死也不要告诉别人！`;

	let emailService = vkmail.createTransport({
		"host": emailConfig[serviceType].host,
		"port": emailConfig[serviceType].port,
		"secure": emailConfig[serviceType].secure, // use SSL
		"auth": emailConfig[serviceType].auth
	});

	try {
		res.sendMailRes = await emailService.sendMail({
			"from": emailConfig[serviceType].auth.user,
			"to": email,
			"cc": emailConfig[serviceType].auth.user, // 由于邮件可能会被当成垃圾邮件，但只要把右键抄送给自己一份，就不会被当成垃圾邮件。
			"subject": subject,
			"text": text
		});
		res.code = 0;
		res.msg = "ok";
		// 发送验证码成功后，设置验证码
		await uniID.setVerifyCode({ code, email, type });
	} catch (err) {
		res.code = -1;
		res.msg = "邮件发送失败";
		res.err = err;
	}

	return res;
};
